package com.ssps.front.rent.controller;

import com.github.pagehelper.PageInfo;
import com.ssps.entity.*;
import com.ssps.front.rent.service.*;
import com.ssps.front.tenant2.utils2.Tenant2Utils;
import com.ssps.front.ternant.util.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lg
 * @time 2020/07/22 15:29:42
 */
@Controller
@RequestMapping("LessorUser")
public class LessorUserController {

    @Autowired
    private LessorUserService lessorUserService;

    @Autowired
    private LessorParkingService lessorParkingService;

    @Autowired
    private LessorUserOrderService lessorUserOrderService;

    @Autowired
    private LessorUserInfoService lessorUserInfoService;

    @Autowired
    private LessorUserCommissionService lessorUserCommissionService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /*
     *  上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值
     *
     * */
    @Value("${uploadFile2.location}")
    private String uploadFileLocation;

    /*
     * 获取端口号
     * */
    @Value("${server.port}")
    private String port;


    @RequestMapping("LessorUserFindAll")
    @ResponseBody
    public List<User> LessorUserFindAll() {
        List<User> users = lessorUserService.findAlls (2);
        return users;
    }

    @RequestMapping("LessorUserParking")
    @ResponseBody
    public List<Parking> LessorUserParking(HttpSession session) {
        User user = (User) session.getAttribute ("");
        List<Parking> parking = lessorParkingService.findAllParking (2);
        System.out.println (parking.get (0).getImg ()+"img");
        return parking;
    }

    @RequestMapping("LessorUserSendsms")
    @ResponseBody
    public String LessorUserSendsms(@RequestBody String uphone) {
        System.out.println (uphone.substring (11, 22));
        String code = lessorParkingService.getCode (uphone.substring (11, 22));


        return "code";

    }

    @RequestMapping("LessorUserVerfity")
    @ResponseBody
    public String LessorUserVerfity(@RequestBody String code, String codes, String newPassword, String newPasswords, HttpSession session) {

        User user = (User) session.getAttribute ("");
        Integer uid = 2;
        String flag = "true";
        String subcode = code.substring (9, 15);
        String subcodes = code.substring (26, 32);

        String newPassword1 = code.substring (49, 55);
        String newPasswords2 = code.substring (73, 79);

        System.out.println (newPassword1 + "qwe");
        System.out.println (newPasswords2 + "qwe");

        if (!subcode.equals (subcodes)) {
            flag = "false1";
            return flag;
        }
        if (!newPassword1.equals (newPasswords2)) {
            flag = "false2";
            return flag;
        }

        if (newPassword1.equals (newPasswords2)) {

            User user1 = lessorUserService.findByUids (uid);
            String salt = Tenant2Utils.getSalt ();
            String md5 = Tenant2Utils.getMD5 (newPassword1, salt);
            user1.setPwd (md5);
            user1.setSalt (salt);
            lessorUserService.updates (user1);
            flag = "success2";
            return flag;
        }

        return flag;
    }

    @RequestMapping("LessorUserFindAllOrder/{page}")
    @ResponseBody
    public Map<String, Object> LessorUserFindAllOrder(@PathVariable Integer page, HttpSession session) {

        Integer pageSize = 1;
        if (page == null) {
            page = 1;
        }

        User user = (User) session.getAttribute ("");

        Map<String, Object> map = new HashMap<> ();

        try {
            Map<String, Object> map1 = lessorParkingService.findByUiid (2, page, pageSize);
            List<Orders> ordersList = (List<Orders>) map1.get ("ordersList");
            PageInfo pageInfo = (PageInfo) map1.get ("pageInfo");
            for (Orders orders : ordersList) {
                System.out.println (orders + "888");
            }
            System.out.println (pageInfo + "999");

            map.put ("ordersList", ordersList);
            map.put ("pageInfo", pageInfo);
            map.put ("msg", true);
        } catch (Exception e) {
            map.put ("msg", false);
            e.printStackTrace ();
        }

        return map;
    }


    @RequestMapping("updateUser")
    @ResponseBody
    public Map<String, Object> updateUser(@RequestBody UserInfo userInfo,@RequestBody User user
                                          ,HttpServletRequest request) {

        System.out.println (userInfo.getAddress ()+ "666");
        Map<String, Object> map = new HashMap<> ();
        try {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            loginUser.setAcount(user.getAcount());
            loginUserInfo.setAddress(userInfo.getAddress());
            loginUserInfo.setBirthday(userInfo.getBirthday());
            loginUserInfo.setUemail(userInfo.getUemail());
            lessorUserService.updateUser(loginUser);
            lessorUserInfoService.updateUserInfo(loginUserInfo);
            map.put("result", "ok");

            map.put ("result", "ok");
        } catch (Exception e) {
            map.put ("result", "flase");
            e.printStackTrace ();
        }
        return map;
    }

    /**
     * 查询用户的所有信息
     *
     * @param request
     * @return
     */
    @RequestMapping("selectOne")
    @ResponseBody
    public Map<String, Object> selectOne(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
          User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            map.put("loginUserInfo", loginUserInfo);

            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /*车库产权上传
     * */
    @RequestMapping("verified")
    @ResponseBody
    public Map<String, Object> verified(MultipartFile idCardFront, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<> ();
        try {
            UserInfo userInfo = (UserInfo) request.getSession ().getAttribute ("loginUserInfo");
            String frontName = idCardFront.getOriginalFilename ();
            File frontFile = null;
            if (frontName != null && !frontName.trim ().equals ("")) {
                String suffix = frontName.substring (frontName.lastIndexOf ("."));
                frontName = UUID.randomUUID ().toString ().replace ("-", "") + suffix;
                frontFile = new File (uploadFileLocation, frontName);
                idCardFront.transferTo (frontFile);
            }
            lessorParkingService.uploadPackageProperty (MyUtils.getLocalIP () + ":" + port + "/upload/" + frontFile.getName (), 6);
            map.put ("result", "ok");
        } catch (IOException e) {
            map.put ("result", "no");
            e.printStackTrace ();
        }
        return map;
    }

    /*
     车库照片上传
    * */
    @RequestMapping("verifieds")
    @ResponseBody
    public Map<String, Object> verifieds(MultipartFile idCardFront, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<> ();

        try {
            UserInfo userInfo = (UserInfo) request.getSession ().getAttribute ("loginUserInfo");
            String frontName = idCardFront.getOriginalFilename ();
            File frontFile = null;
            if (frontName != null && !frontName.trim ().equals ("")) {
                String suffix = frontName.substring (frontName.lastIndexOf ("."));
                frontName = UUID.randomUUID ().toString ().replace ("-", "") + suffix;
                frontFile = new File (uploadFileLocation, frontName);
                idCardFront.transferTo (frontFile);
            }
            lessorParkingService.uploadPackage ("http://"+MyUtils.getLocalIP () + ":" + port + "/upload/" + frontFile.getName (), 6);


            map.put ("result", "ok");
        } catch (IOException e) {
            map.put ("result", "no");
            e.printStackTrace ();
        }
        return map;
    }

    /*
    查看车库评论
    * */
    @RequestMapping("lockComment/{pageNum}")
    @ResponseBody
    public Map<String, Object> lockComment(@PathVariable Integer pageNum, HttpSession session) {
        Integer pageSize = 5;
        if (pageNum == null) {
            pageNum = 1;
        }

        Map<String, Object> map = null;
        try {
            map = new HashMap<> ();

            UserInfo userInfo = (UserInfo) session.getAttribute ("");

            Map<String, Object> map1 = lessorParkingService.findByUiidAndPid (2, pageNum, pageSize);

            List<Comments> commentsList = (List<Comments>) map1.get ("comments");
            PageInfo pageInfo = (PageInfo) map1.get ("pageInfo");

            map.put ("commentsList", commentsList);
            map.put ("pageInfo", pageInfo);
            map.put ("msg", true);
        } catch (Exception e) {
            map.put ("msg", false);
            e.printStackTrace ();
        }
        return map;
    }

    @RequestMapping("authentication")
    @ResponseBody
    public Map<String, Object> authentication(MultipartFile idCardFront, MultipartFile idCardBack, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<> ();
        try {
            UserInfo loginUserInfo = (UserInfo) request.getSession ().getAttribute ("loginUserInfo");
            String frontName = idCardFront.getOriginalFilename ();
            String backName = idCardBack.getOriginalFilename ();
            File frontFile = null;
            File backFile = null;
            if (frontName != null && !frontName.trim ().equals ("")) {
                String suffix = frontName.substring (frontName.lastIndexOf ("."));
                frontName = UUID.randomUUID ().toString ().replace ("-", "") + suffix;
                frontFile = new File (uploadFileLocation, frontName);
                idCardFront.transferTo (frontFile);
            }
            if (backName != null && !backName.trim ().equals ("")) {
                String suffix = backName.substring (backName.lastIndexOf ("."));
                backName = UUID.randomUUID ().toString ().replace ("-", "") + suffix;
                backFile = new File (uploadFileLocation, backName);
                idCardBack.transferTo (backFile);
            }
            lessorUserInfoService.uploadIdCard (MyUtils.getLocalIP () + ":" + port + "/upload/" + frontFile.getName (),
                    MyUtils.getLocalIP () + ":" + port + "/upload/" + backFile.getName (), 6);

            String idcard = lessorUserInfoService.idcard (frontName);

            System.out.println (idcard + "678");

            String[] keys = "住址 出生 姓名 公民身份号码 性别 民族".split (" ");
            Map<String, String> idcardMap = new HashMap<String, String> ();
            for (String key : keys) {
                Pattern p = Pattern.compile (key + ".*?\"words\": \"(.*?)\"");
                Matcher matcher = p.matcher (idcard);
                if (matcher.find ()) {
                    String value = matcher.group (1);
                    //System.out.println(key + " = " + value);
                    idcardMap.put (key, value);
                }
            }
            System.out.println (idcardMap);
            String address = idcardMap.get ("住址");
            String birthday = idcardMap.get ("出生");
            String name = idcardMap.get ("姓名");
            String identity = idcardMap.get ("公民身份号码");

            System.out.println (address + birthday + name + identity + "888");
            lessorUserInfoService.add (address, birthday, name, identity, 13, frontName, backName);

            map.put ("result", "ok");
        } catch (Exception e) {
            e.printStackTrace ();
            map.put ("result", "no");
        }
        return map;
    }

    @RequestMapping("backUserInfo")
    @ResponseBody
    public Map<String, Object> backUserInfo(HttpSession session) {
        Map<String, Object> map = new HashMap<> ();

        UserInfo userInfo = (UserInfo) session.getAttribute ("loginUser");

        UserInfo userInfo1 = lessorUserInfoService.findAll (8);
        map.put ("userInfo1", userInfo1);

        return map;
    }


    @RequestMapping("selectAllParking")
    @ResponseBody
    public Map<String,Object> selectAllParking(HttpSession session){

        Map<String,Object> map=new HashMap<> ();

        UserInfo userInfo = (UserInfo) session.getAttribute ("loginUser");

        List<Parking> allParking = lessorParkingService.findAllParking (2);

        map.put ("allParking",allParking);

        return  map;
    }

    @RequestMapping("selectAllCommission")
    @ResponseBody
    public  Map<String,Object> selectAllCommission(){
            Map<String,Object> map=new HashMap<> ();
            List<Commission> commissionList=lessorUserCommissionService.finAllCommission();
            map.put ("commissionList",commissionList);

        return  map;
    }

    @RequestMapping("addOrder")
    @ResponseBody
    public  Map<String,Object> addOrder(HttpSession session,@RequestBody Orders orders){
        Map<String,Object> map=new HashMap<> ();
         UserInfo userInfo= (UserInfo) session.getAttribute ("loginUser");
        System.out.println (orders.getStarttime ()+"ppp");
        System.out.println (orders.getEndtime ()+"ppp");
        String val = "";
        Random random = new Random();
        val+="AYT";
        for (int i = 1; i <=17; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        orders.setStatus ("未出租");
        orders.setOnumber (val);
        lessorUserOrderService.addOrders(orders);

        Orders orders1 =lessorUserOrderService.selectByonumberOrder(val);
        Date starttime = orders1.getStarttime ();
        Date nowdate = new Date () ;
        long times = (starttime.getTime () - nowdate.getTime ())/1000;
        System.out.println (times);
        String tempTime = times + "";
        redisTemplate.opsForValue ().set ("order:"+orders1.getPid2 (),"1",Long.valueOf (tempTime), TimeUnit.SECONDS);

        return  map;
    }

    /**
     * 填写推荐码
     *
     * @param request
     * @param othercode
     * @return
     */
    @RequestMapping("referralCode")
    public Map<String, Object> referralCode(HttpServletRequest request, @RequestBody String othercode) {
        Map<String, Object> map = new HashMap<>();
        try {
            User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");
            Map<String, String> parse = MyUtils.parse(othercode);
            loginUserInfo.setOthercode(parse.get("othercode"));
            lessorUserInfoService.referralCode(loginUserInfo);
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /*
    上传头像图片
    * */
    @RequestMapping("uploadImg")
    @ResponseBody
    public Map<String, Object> uploadImg(MultipartFile img, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
          /*  User loginUser = (User) request.getSession().getAttribute("loginUser");
            UserInfo loginUserInfo = (UserInfo) request.getSession().getAttribute("loginUserInfo");*/
            UserInfo loginUserInfo=new UserInfo ();

            String imgName = img.getOriginalFilename();
            File imgFile = null;
            if (imgName != null && !"".equals(imgName.trim())) {
                String suffix = imgName.substring(imgName.lastIndexOf("."));
                imgName = UUID.randomUUID().toString().replace("-", "") + suffix;
                imgFile = new File(uploadFileLocation, imgName);
                img.transferTo(imgFile);
            }
            loginUserInfo.setUiid (8);
            loginUserInfo.setUname ("王华");
            loginUserInfo.setImg(MyUtils.getLocalIP() + ":" + port + "/upload/" + imgFile.getName());
            lessorUserInfoService.updateUserInfo(loginUserInfo);
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @RequestMapping("logout")
    @ResponseBody
    public Map<String, Object> logout(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        try {
            request.getSession().invalidate();
            map.put("result", "ok");
        } catch (Exception e) {
            map.put("result", "no");
        }
        return map;
    }

}
